package com.byx.chatclient.view.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.byx.chatclient.R;
import com.byx.chatclient.adapter.SearchGroupAdapter;
import com.byx.chatclient.adapter.SearchUserAdapter;
import com.byx.chatclient.bean.SearchGroupBean;
import com.byx.chatclient.bean.SearchUserBean;
import com.byx.chatclient.bean.UserAndGroup;
import com.byx.chatclient.entity.Constant;
import com.byx.chatclient.entity.Result;
import com.byx.chatclient.entity.ResultCode;
import com.byx.chatclient.entity.User;
import com.byx.chatclient.factory.RetrofitFactory;
import com.byx.chatclient.http.ActionRequest;
import com.byx.chatclient.utils.GradientStatusBarUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Superb
 */
@SuppressLint("NonConstantResourceId")
public class SearchActivity extends AppCompatActivity {
    public static final String USER_EXTRA_KEY = "searchUserKey";
    public static final String GROUP_EXTRA_KEY = "searchGroupKey";
    public static final String USER_BEAN = "user_bean";

    @BindView(R.id.iv_back)
    protected ImageView mIvBack;
    @BindView(R.id.et_search_person)
    protected EditText mEtSearch;
    @BindView(R.id.tv_search)
    protected TextView mTvSearch;
    @BindView(R.id.rv_search_person_simple_result)
    protected RecyclerView mRvSearchUser;
    @BindView(R.id.rv_search_group_simple_result)
    protected RecyclerView mRvSearchGroup;
    @BindView(R.id.ll_see_person_more)
    protected LinearLayout mLlSeeMoreForUser;
    @BindView(R.id.ll_see_group_more)
    protected LinearLayout mLlSeeMoreForGroup;
    @BindView(R.id.rl_user_list)
    protected RelativeLayout mRlUserList;
    @BindView(R.id.rl_group_list)
    protected RelativeLayout mRlGroupList;
    @BindView(R.id.tv_search_failed)
    protected TextView mTvSearchFailed;

    private SearchUserAdapter mUserAdapter;
    private SearchGroupAdapter mGroupAdapter;
    private Unbinder mUnbinder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        mUnbinder = ButterKnife.bind(this);
        GradientStatusBarUtil.getInstance().bind(this).withBackgroundResource(R.drawable.toolbar).init();
        initSearchUserAdapter();
        initSearchGroupAdapter();
        initListener();
    }

    private void initSearchUserAdapter() {
        mUserAdapter = new SearchUserAdapter();
        mRvSearchUser.setLayoutManager(new LinearLayoutManager(this));
        mRvSearchUser.setAdapter(mUserAdapter);
        mUserAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.btn_add_friend){
                    SearchUserBean userBean = mUserAdapter.getItem(position);
                    Intent intent = new Intent(SearchActivity.this,AddFriendActivity.class);
                    intent.putExtra(USER_BEAN,userBean);
                    startActivity(intent);
                }
            }
        });
        mUserAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String userId = mUserAdapter.getItem(position).getLoginId();
                User user = new User();
                user.setLoginId(userId);
                Intent intent = new Intent(SearchActivity.this,PersonDetailsActivity.class);
                intent.putExtra(Constant.PERSON_ID,user);
                startActivity(intent);
            }
        });
    }

    private void initSearchGroupAdapter() {
        mGroupAdapter = new SearchGroupAdapter();
        mRvSearchGroup.setLayoutManager(new LinearLayoutManager(this));
        mRvSearchGroup.setAdapter(mGroupAdapter);
        mGroupAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                Long groupId = mGroupAdapter.getItem(position).getGroupId();
            }
        });
        mGroupAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Long groupId = mGroupAdapter.getItem(position).getGroupId();

            }
        });
    }


    private void initListener() {
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mTvSearch.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_search,R.id.ll_see_person_more,R.id.ll_see_group_more,R.id.et_search_person})
    protected void onClick(View view){
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search:
                mEtSearch.clearFocus();
                String searchContent = mEtSearch.getText().toString();
                searchUserAndGroup(searchContent);
                break;
            case R.id.ll_see_person_more:
                String searchUserKey = mEtSearch.getText().toString();
                Intent intent = new Intent(SearchActivity.this,SearchMoreActivity.class);
                intent.putExtra(USER_EXTRA_KEY,searchUserKey);
                startActivity(intent);
                break;
            case R.id.ll_see_group_more:
                String searchGroupKey = mEtSearch.getText().toString();
                Intent it = new Intent(SearchActivity.this,SearchMoreActivity.class);
                it.putExtra(GROUP_EXTRA_KEY,searchGroupKey);
                startActivity(it);
                break;
            case R.id.et_search_person:
                mRlUserList.setVisibility(View.GONE);
                mRlGroupList.setVisibility(View.GONE);
                break;
            default:break;
        }
    }

    private void searchUserAndGroup(String searchContent) {
        RetrofitFactory.getBean(ActionRequest.class).fuzzySearch(searchContent)
                .enqueue(new Callback<Result<UserAndGroup>>() {
                    @Override
                    public void onResponse(@NonNull Call<Result<UserAndGroup>> call, @NonNull Response<Result<UserAndGroup>> response) {
                        if (response.isSuccessful()){
                            Result<UserAndGroup> result = response.body();
                            if (result != null && result.getCode().equals(ResultCode.SUCCESS.code())){
                                List<SearchUserBean> userBeans = result.getData().getUserBeans();
                                List<SearchGroupBean> groupBeans = result.getData().getGroupBeans();

                                boolean noUsers = userBeans == null || userBeans.isEmpty();
                                boolean noGroups = groupBeans == null || groupBeans.isEmpty();

                                if (noUsers && noGroups){
                                    mTvSearchFailed.setVisibility(View.VISIBLE);
                                    mRlUserList.setVisibility(View.GONE);
                                    mRlGroupList.setVisibility(View.GONE);
                                }
                                if (!noUsers){
                                    mUserAdapter.setList(userBeans);
                                    mTvSearchFailed.setVisibility(View.GONE);
                                    mRlUserList.setVisibility(View.VISIBLE);
                                }
                                if (!noGroups){
                                    mGroupAdapter.setList(groupBeans);
                                    mTvSearchFailed.setVisibility(View.GONE);
                                    mRlGroupList.setVisibility(View.VISIBLE);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<Result<UserAndGroup>> call, @NonNull Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        mUnbinder.unbind();
        super.onDestroy();
    }
}